﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace MyWPF.Models.TCP.TCPClient
{
    public class TCPClientHelper : ITCPClient
    {
        #region 委托传入事件
        public delegate void MessageEventHandler(string message);

        private MessageEventHandler messageHandler;

        public TCPClientHelper(MessageEventHandler handler)
        {
            this.messageHandler = handler;
        }
        #endregion


        public TcpClient client = new TcpClient();

        public async void Connect(TCPClientContext ClientContext)
        {
            while (true)
            {
                await Task.Delay(1000);
                try
                {
                    client = new TcpClient();
                    client.Connect(ClientContext.IP, ClientContext.Port);

                    // 不断循环接收消息
                    while (true)
                    {
                        NetworkStream stream = client.GetStream();
                        byte[] buffer = new byte[1024];
                        int bytesRead = stream.Read(buffer, 0, buffer.Length);
                        string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);

                        // 根据收到的消息触发不同的事件，需要指定一个委托
                        messageHandler(message);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
                finally
                {
                    client.Close();
                }

                if (!ClientContext.AutoLink)
                    break;
            }
            
        }

        public void Write(string Message)
        {
            NetworkStream stream = client.GetStream();
            byte[] bytes = Encoding.ASCII.GetBytes(Message);
            stream.Write(bytes,0,bytes.Length);
        }
    }
}
